package com.jf.cloud.common.mongodb.util;

import com.jf.cloud.common.database.dto.PageDTO;
import com.jf.cloud.common.database.util.PageUtil;
import com.jf.cloud.common.database.vo.PageVO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * mongoDB分页工具
 * @author zz
 */
@Component
public class MongoPageUtil {

    private final Logger logger = LoggerFactory.getLogger(MongoPageUtil.class);

    private final MongoTemplate mongoTemplate;

    @Autowired
    public MongoPageUtil(MongoTemplate mongoTemplate) {
        this.mongoTemplate = mongoTemplate;
    }

    public <T> PageVO<T> doPage(Class<T> clazz, PageDTO mongoPageDTO, Query query) {
        long total = mongoTemplate.count(query, clazz);

        int skip = mongoPageDTO.getPageSize() * (mongoPageDTO.getPageNum() - 1);
        query.skip(skip).limit(mongoPageDTO.getPageSize());

        logger.info("构建MongoPageUtil查询语句： {}", query);

        List<T> list = mongoTemplate.find(query, clazz);

        PageVO<T> mongoPageVO = new PageVO<>();
        mongoPageVO.setTotal(total);
        mongoPageVO.setList(list);
        mongoPageVO.setPages(PageUtil.getPages(total, mongoPageDTO.getPageSize()));
        return mongoPageVO;
    }
}

